package com.cn.sl.server.config.web

import cn.dev33.satoken.interceptor.SaInterceptor
import com.cn.sl.server.common.constant.Constant
import com.cn.sl.server.config.traceid.TraceIdInterceptor
import com.cn.sl.server.util.objectMapper
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.http.converter.ByteArrayHttpMessageConverter
import org.springframework.http.converter.HttpMessageConverter
import org.springframework.http.converter.StringHttpMessageConverter
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter
import org.springframework.web.servlet.config.annotation.CorsRegistry
import org.springframework.web.servlet.config.annotation.EnableWebMvc
import org.springframework.web.servlet.config.annotation.InterceptorRegistry
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer
import java.nio.charset.StandardCharsets


/**
 * web相关配置
 *
 * @author 阮雪峰
 */
@Configuration
@EnableWebMvc
class WebConfig : WebMvcConfigurer {
    /**
     * 跨域
     *
     * @param registry registry
     * @author 阮雪峰
     */
    override fun addCorsMappings(registry: CorsRegistry) {
        registry.addMapping("/**")
            .allowedOriginPatterns("*")
            .allowedMethods("*")
            .allowedHeaders("*")
            .exposedHeaders("filename")
            .allowCredentials(true)
            .maxAge(3600)
    }

    /**
     * 解决Long类型id在前端丢失精度问题
     *
     * @param converters converters
     * @author 阮雪峰
     */
    override fun configureMessageConverters(converters: MutableList<HttpMessageConverter<*>?>) {
        converters.add(ByteArrayHttpMessageConverter())
        converters.add(StringHttpMessageConverter(StandardCharsets.UTF_8))
        converters.add(MappingJackson2HttpMessageConverter(objectMapper))
    }

    @Bean
    fun permissionInterceptor(): SaInterceptor {
        return SaInterceptor()
    }

    override fun addInterceptors(registry: InterceptorRegistry) {
        registry.addInterceptor(TraceIdInterceptor())
        registry.addInterceptor(permissionInterceptor())
            .addPathPatterns("/**")
            .excludePathPatterns(
                Constant.ADMIN_ROOT + "/login",
                "/swagger-ui.html",
                "/swagger**/**",
                "/**/api-docs/**"
            )

    }

    override fun addResourceHandlers(registry: ResourceHandlerRegistry) {
        registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/")
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/")
    }
}